<meta charset="utf-8">
<!--<script src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=E4805d16520de693a3fe707cdc962045"></script>-->
<script src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=UXNfXeDbwzkcGkSugykBYF8kiuweOAAY"></script>
<script src="./bmap.point.js"></script>
 <style>
    body,
    html,
    #container {
        overflow: hidden;
        width: 100%;
        height: 100%;
        margin: 0;
        font-family: "微软雅黑";
    }
    
.bpoint{
            color: #fff;
            background:#059c49;
            opacity: 0.8;
            width: 100px;
            height: 100px;
            vertical-align: middle;
            text-align: center;
            border-radius: 50%;
            cursor: pointer;
            margin: -50px 0 0 -50px;
            font-size: 18px;
    }
    .bpoint:hover{background: red}
    .bpoint p{        padding-top: 11px;    }
    

     .menu{top: 0px;    position: absolute;    z-index: 2000;left: -20px;top: -5px;    color: #000;display: none;}
    .menu dd{margin: 0px;width: 150px;cursor: pointer}
    .menu dl{position: absolute;border: 1px scrollbar solid;background: #fff;    opacity: 0.8;margin: 0px;padding: 0px;}
    .menu #key{display: none;}
    .menu #key input{width:130px;border: 0px;outline:none;}
    .menu dd>dl{display: none;  margin-left: 150px;margin-top: -20px;}
    .menu dd:hover{background-color:cornsilk;font-weight: bold;}
    .menu dd:hover>dl{display: block}

</style>
<div id="search" class="menu">
    <dl>
        <dd id="key"><i  class="icon-search"> s </i><input type="text" name="key"  /><i  class="icon-search-delete" > c</i> </dd>
        <dd  >存储路径<dl id='path'><dd onclick="addPath()">新增</dd></dl></dd>
        <dd >时间<dl id="time"></dl></dd>
        <dd >地址<dl id="name"></dl></dd>
        <dd  onclick='events.zoomend(0,1)'>重置搜索条件</dd>
        <dd>打开<dl>
            <dd  onclick='bridge("openConfig")'>目录管理</dd>
            <dd  onclick='bridge("openMain")'>主页</dd>
        </dl></dd>
    </dl>
</div>

<div id="container"></div>
<script>
var bridgeDemo={
    getPoints:(v)=>{
        return  [ { count: 1669, name: "宝安", x: 113.89006042480469, y: 22.56084442138672, }, { count: 494, name: "东莞", x: 113.75823211669922, y: 23.026996612548828, }, { count: 1895, name: "龙岗", x: 114.25444030761719, y: 22.72633171081543, }, 
            { count: 2606, id:11,name: "福田", x: 114.06153106689453, y: 22.527225494384766,vg:"114.111476,22.53826;114.11101,22.553809;114.110718,22.572663;114.104188,22.571248;114.09912,22.570126;114.097927,22.570907;114.096157,22.57382;114.092451,22.575672;114.088531,22.575548;114.086225,22.574988;114.082806,22.580751;114.082324,22.583101;114.080293,22.585229;114.074145,22.590958;114.070218,22.59237;114.064793,22.592853;114.062517,22.59162;114.061184,22.590877;114.060502,22.590254;114.060232,22.589301;114.06008,22.588173;114.059228,22.587632;114.058366,22.587959;114.057604,22.588363;114.055736,22.588149;114.054432,22.588279;114.053419,22.588753;114.052645,22.589547;114.048979,22.589615;114.047511,22.589768;114.043953,22.588989;114.042626,22.589326;114.042053,22.589337;114.039096,22.588282;114.037909,22.587766;114.035805,22.587737;114.033765,22.58794;114.032558,22.588289;114.031583,22.588167;114.029275,22.586823;114.028562,22.586321;114.025686,22.585283;114.023356,22.585214;114.022813,22.585474;114.020037,22.585583;114.014297,22.583828;114.013062,22.582543;114.011882,22.581938;114.011372,22.578076;114.011446,22.576973;114.011664,22.575449;114.011721,22.57455;114.011346,22.573541;114.010378,22.572445;114.009725,22.57081;114.009912,22.568585;114.010109,22.567706;114.010248,22.56665;114.010941,22.565995;114.011322,22.565225;114.011643,22.564569;114.01173,22.563839;114.011809,22.562513;114.010317,22.562116;114.008778,22.561978;114.007665,22.56197;114.005656,22.561548;114.003866,22.561101;114.004507,22.56024;114.004585,22.558977;114.004513,22.557799;114.004826,22.556744;114.005391,22.556209;114.006165,22.555908;114.005901,22.555148;114.004546,22.554969;114.003896,22.554681;114.002525,22.552873;114.003285,22.551603;114.00332,22.550567;114.002976,22.549448;114.003063,22.54727;114.003004,22.545363;114.003217,22.543581;114.003604,22.541511;114.003863,22.540152;114.004089,22.538911;114.00331,22.538728;114.001703,22.539097;114.001542,22.538457;114.002152,22.537501;114.001614,22.536624;114.000722,22.536727;114.000297,22.536231;113.999936,22.535205;113.999847,22.533294;114.00258,22.524318;114.006427,22.511619;114.021191,22.507073;114.031597,22.506086;114.048162,22.509099;114.064504,22.50594;114.067075,22.509363;114.068667,22.514205;114.075949,22.520487;114.080682,22.521372;114.08719,22.519015;114.094594,22.525418;114.089216,22.532223;114.094151,22.535578;114.107081,22.538324" }, 
            { count: 8, name: "南沙", x: 113.53143310546875, y: 22.80792808532715, }, { count: 14, name: "其他", x: 113.36091613769531, y: 23.00429916381836, }, { count: 2221, name: "罗湖", x: 114.13809967041016, y: 22.554670333862305, }, { count: 3, name: "中山", x: 113.3991470336914, y: 22.52403450012207, }, { count: 452, name: "盐田", x: 114.24333190917969, y: 22.563232421875, }, { count: 2630, name: "南山", x: 113.93694305419922, y: 22.53907012939453, }, { count: 648, name: "惠州", x: 114.42334747314453, y: 23.116409301757812, }, { count: 85, name: "深圳周边", x: 113.92813873291016, y: 22.507844924926758, } 
        ];
    },
    getPostion:()=>{    
        return {x:114.06153,y:22.527225,z:12};
    },
    openId:(id)=>{
        alert(id);
    },
    addPath:()=>{
        alert(11);
    }
}
window.bridge=function(name,params=[],func=null){
    if(typeof(params)=="function") {
        func=params;
        params=[];
    }
    // var rt=bridgeDemo[name](params)
    // if( func) func(rt);
    // return
    //https://www.cnblogs.com/huangyichun/p/6142263.html
    function ajax(url,data={},func=null,type='GET'){
        var xhr =new XMLHttpRequest() || new ActiveXObject("Msxml2.XMLHTTP") || new ActiveXObject("Microsoft.XMLHTTP");
        //data.call &&  func=data,data={} 
        xhr.onreadystatechange = function(){
                if(xhr.readyState==4){
                    if(xhr.status==200||xhr.status==304){
                        var data = xhr.responseText;
                        if(xhr.getResponseHeader('Content-Type').match(/json/i)) data=JSON.parse(data);
                        return func(data);
                    }
                }
                //console.log(xhr)
            }
        var qa=[],k;
        for  (k in params) qa.push(`${k}=${params[k]}`)
        if(qa.length>0)  url+=url.match(/\?/)? "&":'?',url+=qa.join("&")  
        xhr.open(type,url,true);
        xhr.send(null)
    }
    // location.origin+
    ajax("/api/"+name,params,function(data){
        if(func) func(data);
    })
}


/**
 * https://map.fang.com/sz/?refer=sy_seach
 * https://mapopen-pub-jsapi.bj.bcebos.com/jsapi/reference/jsapi_webgl_1_0.html#a3b8
 * https://lbsyun.baidu.com/index.php?title=jspopularGL/guide/addOverlay
 * https://lbsyun.baidu.com/jsdemo.htm#eAddLabel
 */
/**
 * 添加点覆盖物 
 * @param object p {x:横坐标,y:纵坐标,name:地点名称,count:数量,vg:矢量图范围,id:范围id}
 * @return {undefined}
 */
function addPoint(p,point=''){
    if(!point) point=new BMapGL.Point(p.x, p.y)
    var marker = new BPoint(point,{
        className:"bpoint",
        innerHTML:"<p><b>"+p.name+"</b><br/> \n"+p.count+"张</p>",
        id:p.id,
        onclick:function(e){
            console.log(e);
            bridge('openId',{id:this.id},function(files){
//                window.localStorage.setItem('pics',JSON.stringify(files))
//                window.open("./pics.html?id="+p.id)    
            });
        },
        onmouseover :function(e){
            if(!p.vg) return true;
            var hole = new BMapGL.Polygon([p.vg,p.vg], {
                strokeColor:'red',
                fillOpacity: 0.1
            });
           addPoint.hole=hole;
            map.addOverlay(hole);
        },
        onmouseout:function(e){
            if(addPoint.hole) map.removeOverlay(addPoint.hole);
        }
    });
    
    function getname(){
        var myGeo = new BMapGL.Geocoder();      
        // 根据坐标得到地址描述    
        myGeo.getLocation(new BMapGL.Point(p.x,p.y), function(result){      
            if (result){      
              alert(result.address);      
            }      
        });
    }
    // 将标注添加到地图
    map.addOverlay(marker);
}

function addMenu(txtMenuItem){
    this.bind=function(){
        var menu = new BMapGL.ContextMenu();
        menu.addItem(new BMapGL.MenuItem(" ", function(){return false;},{width:100,id:"menu"}));
        map.addContextMenu(menu);
        setTimeout(function(){
            document.getElementById('menu').append(document.getElementById('search'))
            //document.getElementById('menu').style.display='none';
            },500);
        document.getElementById('search').style.display='block';
        
    }
    this.onclick=function(event){
        if(event.button!=0) return 
        console.log([this.name,this.value])
        events.zoomend(this.name,this.value);
    }
    this.updateOne=function(name,values,path){
             var dl=document.getElementById(name),ddDemo=document.createElement('dd'),dd;
             dl.innerHTML='';
             if(path) {
                dl.value=dl.previousSibling.data=path;
             }
             values.forEach((v)=>{
                dd=ddDemo.cloneNode()
                 dd.innerText=v
                 dd.name=name; dd.value=dl.value? dl.value+v :v                 
                 dd.onclick= menu.onclick
                 dl.append(dd)   
             })
             //dl.parentElement.style.display= (values.length) ? 'black': 'none'
        }
        this.update=function(current,options){
            for (name in options) this.updateOne(name,options[name],current[name])
        }
        return this
}

// map.setTrafficOn(); // 叠加路况图层
// map.setTrafficOff(); // 关闭路况图层
var controls=[
    new BMapGL.ScaleControl(),  // 添加比例尺控件
    new BMapGL.LocationControl({        //创建定位控件
        // 控件的停靠位置（可选，默认左上角）
        anchor: BMAP_ANCHOR_TOP_RIGHT,
        // 控件基于停靠位置的偏移量（可选）
        offset: new BMapGL.Size(20, 20)
    }),
     //new BMap.PanoramaControl() //全景控件   stCtrl.setOffset(new BMap.Size(20, 20));
];
var events={
        tilesloaded:()=>{       //地图加载完成
             menu.bind()
        },
        click:(e)=>{         //'点击位置经纬度：' + e.latlng.lng + ',' + e.latlng.lat
            
        },
        zoomend :(e,v)=>{  //地图缩放结束事件 
           var b= map.getBounds();
           var params={
               zoom:parseInt(map.getZoom()),
               range:[b.sw.lng,b.ne.lng,b.sw.lat,b.ne.lat],          //界限 ne西北,sw东南
           };
           //附加字段 过滤获 清空
           if(v)  {
               e? events.zoomend.filter[e]=v :events.zoomend.filter={}
           }
           for(i in events.zoomend.filter) params[i]=events.zoomend.filter[i]
           var str_params=JSON.stringify(params)
           if(events.zoomend.params==str_params) return;
           events.zoomend.params=str_params
           
           bridge('getPoints',params,(data)=>{
                var points=data.points,options=data.options,current=data.current;
                map.clearOverlays();
                map.getOverlays().forEach(function(p){
                    map.removeOverlay(p)
                })
                var pointArr=[]
                points.forEach((p)=>{ 
//                    addPoint(p);  
                    pointArr.push(new BMapGL.Point(p.x,p.y));
                })
               // console.log(points);
                new BMapGL.Convertor().translate(pointArr,COORDINATES_WGS84, COORDINATES_BD09,function(data){
                    //console.log(data.points)
                    data.points.forEach(function(p,i){
                        console.log([points[i],p])
                        addPoint(points[i],p);
                    })
                })
                menu.update(current,options)
           });
        },
        moveend:(e)=>{ events.zoomend();}
};
events.zoomend.filter={}


var map = new BMapGL.Map('container');
map.enableScrollWheelZoom(true);
window.menu=addMenu();
controls.forEach((c)=>{map.addControl(c);})      // 将控件添加到地图上
for(var ev in events)   map.addEventListener(ev,events[ev]);    

bridge('getPostion',function(pos){
     map.centerAndZoom(new BMapGL.Point(pos.x,pos.y), pos.z);
     events.zoomend();
});
//运动轨迹   https://lbsyun.baidu.com/jsdemo.htm#fAnimationPause
//var path = [[116.297611, 40.047363],[116.302839, 40.048219],[116.308301, 40.050566]], point = [];
//for (var i = 0; i < path.length; i++)    point.push(new BMapGL.Point(path[i][0], path[i][1]));
//trackAni = new BMapGLLib.TrackAnimation(bmap, new BMapGL.Polyline(point), { overallView: true,    tilt: 30,    duration: 20000,    delay: 300});
//trackAni.start();    trackAni.pause();  ,  trackAni.continue();
    
//var local =  new BMapGL.LocalSearch(map, {renderOptions: {map: map, autoViewport: false}});  
//local.searchNearby('餐馆',mPoint,1000);
</script>